package com.ndd.controller;

import com.ndd.constant.Constants;
import com.ndd.dto.CartDTO;
import com.ndd.dto.CartNumUpdateDTO;
import com.ndd.result.R;
import com.ndd.service.CartService;
import com.ndd.utils.JwtUtils;
import com.ndd.vo.CartVO;
import com.ndd.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController //整个控制器返回的都是数据
@RequestMapping("/api/cart") // 访问的url的上级或者上两级目录
@Slf4j //日志的优先级默认是info
public class CartController {
    @Autowired
    private CartService cartService;
    @PostMapping("addCart")
    public R<Void> addCartController(@RequestBody @Validated CartDTO cartDTO, HttpServletRequest request){
        //加入购物车明确用户身份：知道谁在加入购物车
        String token = request.getHeader(Constants.TOKEN_HEADER);
        //获取用户身份:登录的用户身份
        UserLoginVO userLoginVO = JwtUtils.parseToken(token);
        //调用业务层进行购物车的加入
        cartService.addCart(cartDTO,userLoginVO);
        return R.ok();
    }
    @GetMapping("list")
    public R<List<CartVO>> getcartlist(@RequestBody UserLoginVO userLoginVO){
        List<CartVO> cartlist = cartService.getCartlist(userLoginVO);
        return R.ok(cartlist);
    }

    @PostMapping("updateNum")
    public R<Void> updateProductNum(@RequestBody @Validated CartNumUpdateDTO cartNumUpdateDTO, HttpServletRequest request){
        //购物车添加商品数量明确用户身份：知道谁在添加数量
        String token = request.getHeader(Constants.TOKEN_HEADER);
        //获取用户身份:登录的用户身份
        UserLoginVO userLoginVO = JwtUtils.parseToken(token);
        cartService.updateCartNum(cartNumUpdateDTO,userLoginVO);
        return R.ok();
    }
}




